import { ChangeEvent, InputHTMLAttributes, RefObject } from 'react';

import { ReactComponent as CloseIcon } from '@/assets/images/shared/CloseMDThin.svg';
import { ReactComponent as SearchIcon } from '@/assets/images/shared/icon-search.svg';
import { useParams } from '@/shared/lib/hooks';
import { useRouter } from 'next/router';
import { useUpdateEffect } from 'usehooks-ts';

import cs from './Search.module.scss';

export const Search = ({
  innerRef,
  ...props
}: { innerRef?: RefObject<HTMLInputElement> } & InputHTMLAttributes<HTMLInputElement>) => {
  const [value, setValue] = useParams<string>({ key: 'search', deserialize: (v) => v || '' });
  const onChange = (e: ChangeEvent<HTMLInputElement>) => {
    const { value } = e.target;

    setValue(value);
  };
  const router = useRouter();
  useUpdateEffect(() => {
    const value = router?.query?.search?.toString() || '';
    setValue(() => value);
  }, [router?.query?.search]);
  const handleClear = () => {
    setValue(() => '');
    if (!innerRef?.current) {
      return;
    }
    innerRef.current.focus();
  };

  return (
    <label className={cs.search} htmlFor="search">
      <div className={cs.search_icon} onClick={handleClear}>
        <SearchIcon />
      </div>
      <input
        className={cs.input}
        id="search"
        onChange={onChange}
        placeholder="Поиск"
        ref={innerRef}
        type="text"
        value={value || ''}
        {...props}
        autoComplete="off"
      />
      <div className={cs.search_clear}>
        {!!value && (
          <button className={cs.search_clear_button} onClick={handleClear} type="button">
            <CloseIcon />
          </button>
        )}
      </div>
    </label>
  );
};
